package com.shuqi.database.dao.impl;

import java.sql.SQLException;
import java.util.List;

import android.content.Context;
import android.text.TextUtils;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.j256.ormlite.stmt.Where;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.Constant;
import com.shuqi.common.utils.Log4an;
import com.shuqi.database.dao.OrmBaseDao;
import com.shuqi.database.model.BookInfo;

/**
 * 
 * 书籍信息操作逻辑
 * 
 * @author hxp
 * 
 */
public class BookInfoDao extends OrmBaseDao {

    private static BookInfoDao mInstance;

    private RuntimeExceptionDao<BookInfo, Integer> mDao = ShuqiDatabaseHelper.getHelper(
            ShuqiApplication.getContext()).getRuntimeExceptionDao(BookInfo.class);

    private BookInfoDao(Context context) {

    }

    public static synchronized BookInfoDao getInstance() {
        if (mInstance == null) {
            mInstance = new BookInfoDao(ShuqiApplication.getContext());
        }
        return mInstance;
    }

    /**
     * 根据sourceId 和 bookId 获取对应书籍信息
     * 
     * @param context
     * @param sourceId
     * @param bookId
     * @param uid
     * @return
     */
    public BookInfo getBookInfo(String sourceId, String bookId, String uid) {
        if (TextUtils.isEmpty(uid) || TextUtils.isEmpty(bookId)) {
            return null;
        }
        QueryBuilder<BookInfo, Integer> queryBuilder = mDao.queryBuilder();
        try {
            Where<BookInfo, Integer> where = queryBuilder.where();
            where.eq("book_id", bookId);
            if (TextUtils.isEmpty(sourceId)) {
                sourceId = "";
            }
            where.and().eq("source_id", sourceId);
            where.and().eq("user_id", uid);
            List<BookInfo> bookInfoList = queryBuilder.query();
            if (bookInfoList != null && bookInfoList.size() > 0) {
                return bookInfoList.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取浏览历史记录
     * 
     * @param context
     * @param uid
     * @return
     */
    public List<BookInfo> getBrowsingHistorys(String uid) {
        if (TextUtils.isEmpty(uid)) {
            return null;
        }
        QueryBuilder<BookInfo, Integer> queryBuilder = mDao.queryBuilder();
        try {
            Where<BookInfo, Integer> where = queryBuilder.where();
            where.eq("book_history_state", BookInfo.IN_HISTORY);
            where.and().eq("user_id", uid);
            queryBuilder.orderBy("book_update_time", false);
            List<BookInfo> bookInfoList = queryBuilder.query();
            return bookInfoList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /***
     * 获取指定书籍的书籍基本信息
     * @param uid
     * @param bookIds
     * @return
     */
    public List<BookInfo> getBookInfoOfShuqiBookMark(String uid,List<String> bookIds){
        QueryBuilder<BookInfo, Integer> queryBuilder = mDao.queryBuilder();
        try {
            Where<BookInfo, Integer> where = queryBuilder.where();
            where.in("book_id", bookIds);
            where.and().eq("source_type", BookInfo.SOURCE_TYPE_SHUQI);
            where.and().eq("user_id", uid);
            List<BookInfo> bookInfoList = queryBuilder.query();
            return bookInfoList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加或更新书籍信息
     * 
     * @param context
     * @param info
     * @return
     */
    public int saveOrUpdateBookInfo(BookInfo info) {
        int num = -1;
        if (info != null) {
            if (TextUtils.isEmpty(info.getUserId())) {
                info.setUserId(Constant.GUEST_USER_ID);
            }
            String bookId = info.getBookId();
            if (TextUtils.isEmpty(info.getSourceId())) {
                info.setSourceId("");
            }
            String sourceId = info.getSourceId();
            String uid = info.getUserId();
            if (!TextUtils.isEmpty(bookId) && !TextUtils.isEmpty(uid)) {
                BookInfo oldInfo = getBookInfo(sourceId, bookId, uid);
                if (oldInfo != null) {
                    if (!TextUtils.isEmpty(info.getBookAuthorName())) {
                        oldInfo.setBookAuthorName(info.getBookAuthorName());
                    }
                    if (!TextUtils.isEmpty(info.getBookCoverImgUrl())) {
                        oldInfo.setBookCoverImgUrl(info.getBookCoverImgUrl());
                    }
                    if (!TextUtils.isEmpty(info.getBookHideState())) {
                        oldInfo.setBookHideState(info.getBookHideState());
                    }
                    if (info.getBookMaxOid() > oldInfo.getBookMaxOid()) {
                        oldInfo.setBookMaxOid(info.getBookMaxOid());
                    }
                    if (!TextUtils.isEmpty(info.getBookName())) {
                        oldInfo.setBookName(info.getBookName());
                    }
                    if (info.getBookPayMode() != BookInfo.ILLEGAL_VALUE) {
                        oldInfo.setBookPayMode(info.getBookPayMode());
                    }
                    if (info.getBookPrice() != BookInfo.ILLEGAL_VALUE) {
                        oldInfo.setBookPrice(info.getBookPrice());
                    }
                    if (info.getBookPayState() != BookInfo.ILLEGAL_VALUE) {
                        oldInfo.setBookPayState(info.getBookPayState());
                    }

                    if (info.getBookStatus() != null) {
                        oldInfo.setBookStatus(info.getBookStatus());
                    }
                    oldInfo.setBookUpdateTime(System.currentTimeMillis());
                    if (!TextUtils.isEmpty(info.getBookWordCount())) {
                        oldInfo.setBookWordCount(info.getBookWordCount());
                    }
                    if (info.getCoverHideState() != BookInfo.ILLEGAL_VALUE) {
                        oldInfo.setCoverHideState(info.getCoverHideState());
                    }
                    if (info.getReadHideState() != BookInfo.ILLEGAL_VALUE) {
                        oldInfo.setReadHideState(info.getReadHideState());
                    }
                    if (info.getBookHistoryState() != BookInfo.ILLEGAL_VALUE) {
                        oldInfo.setBookHistoryState(info.getBookHistoryState());
                    }
                    
                    if(BookInfo.ILLEGAL_VALUE != info.getSourceType()){
                        oldInfo.setSourceType(info.getSourceType());
                    }
                    if(info.getUpdateCatalog() == BookInfo.UPDATE_CATALOG_YES){
                        oldInfo.setUpdateCatalog(info.getUpdateCatalog());
                    }else{
                        oldInfo.setUpdateCatalog(BookInfo.UPDATE_CATALOG_NO);
                    }
                    num = mDao.update(oldInfo);
                } else {
                    num = mDao.create(info);
                }
            }
        }
        return num;
    }

    /**
     * 删除浏览历史记录
     * 
     * @param context
     * @param uid
     * @return
     */
    public boolean delBrowsingHistory(String uid) {
        if (TextUtils.isEmpty(uid)) {
            return false;
        }
        UpdateBuilder<BookInfo, Integer> updateBuidler = mDao.updateBuilder();
        try {
            Where<BookInfo, Integer> where = updateBuidler.where();
            where.eq("user_id", uid);
            updateBuidler.updateColumnValue("book_history_state", BookInfo.UNIN_HISTORY);
            int count = updateBuidler.update();
            return count > 0 ? true : false;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除书籍
     * 
     * @param bookId
     * @param sourceId
     * @param userId
     */
    public void delBookInfo(String bookId, String sourceId, String userId) {
        DeleteBuilder<BookInfo, Integer> deleteBuilder = mDao.deleteBuilder();
        try {
            Where<BookInfo, Integer> where = deleteBuilder.where();
            where.eq("book_id", bookId);
            if (TextUtils.isEmpty(sourceId)) {
                sourceId = "";
            }
            where.and().eq("source_id", sourceId);
            where.and().eq("user_id", userId);
            deleteBuilder.delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     * 更新书签后更新书籍信息
     * 
     * @param bookId
     * @param sourceId
     * @param uid
     */
    public void updateBookInfoAfterBookMark(String bookId, String sourceId, String uid) {
        UpdateBuilder<BookInfo, Integer> updateBuidler = mDao.updateBuilder();
        try {
            Where<BookInfo, Integer> where = updateBuidler.where();
            where.eq("user_id", uid);
            if (sourceId == null) {
                where.and().eq("source_id", "");
            } else {
                where.and().eq("source_id", sourceId);
            }
            where.and().eq("book_id", bookId);

            updateBuidler.updateColumnValue("book_down_count", 0);
            updateBuidler.updateColumnValue("book_max_oid", 0);

            updateBuidler.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取某用户下所有自动购买的书籍
     * 
     * @param uid
     * @return
     */
    public List<BookInfo> getAllAutoBuyBook(String uid) {
        if (TextUtils.isEmpty(uid)) {
            return null;
        }
        QueryBuilder<BookInfo, Integer> queryBuilder = mDao.queryBuilder();
        try {
            Where<BookInfo, Integer> where = queryBuilder.where();
            where.eq("book_auto_buy_state", BookInfo.AUTO_BUY);
            where.and().eq("user_id", uid);
            List<BookInfo> bookInfoList = queryBuilder.query();
            return bookInfoList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 更新某本书的自动购买状态
     * 
     * @param bookId
     * @param sourceId
     * @param uid
     * @param autoState
     */
    public void updateAutoBuyBookState(String bookId, String sourceId, String uid, int autoState) {
        UpdateBuilder<BookInfo, Integer> updateBuidler = mDao.updateBuilder();
        try {
            Where<BookInfo, Integer> where = updateBuidler.where();
            where.eq("user_id", uid);
            if (sourceId == null) {
                where.and().eq("source_id", "");
            } else {
                where.and().eq("source_id", sourceId);
            }
            where.and().eq("book_id", bookId);
            updateBuidler.updateColumnValue("book_auto_buy_state", autoState);
            updateBuidler.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public int updateDowncount(String uid, String bookId, int downCount) {
        if (TextUtils.isEmpty(uid) || TextUtils.isEmpty(bookId)) {
            return -1;
        }
        try {
            UpdateBuilder<BookInfo, Integer> updateBuidler = mDao.updateBuilder();
            Where<BookInfo, Integer> where = updateBuidler.where();
            where.eq("user_id", uid);
            where.and().eq("book_id", bookId);
            updateBuidler.updateColumnValue("book_down_count", downCount);
            return updateBuidler.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
    
    /***
     * 检查更新需要更新目录，更新书籍信息表目录更新字段为：需要更新
     * @param uid
     * @param bookId
     * @return
     */
    public int callBookCatalogNeedUpdate(String uid, List<String> bookIds,boolean isShuQiMark){
        if (TextUtils.isEmpty(uid) || bookIds==null || bookIds.size() < 1) {
            return -1;
        }
        try {
            UpdateBuilder<BookInfo, Integer> updateBuidler = mDao.updateBuilder();
            Where<BookInfo, Integer> where = updateBuidler.where();
            where.in("book_id", bookIds);
            where.and().eq("user_id", uid);
            where.and().eq("source_type", isShuQiMark?BookInfo.SOURCE_TYPE_SHUQI:BookInfo.SOURCE_TYPE_SHEENME);
            updateBuidler.updateColumnValue("update_catalog", BookInfo.UPDATE_CATALOG_YES);
            return updateBuidler.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

}
